import { useMemo, useState, useRef } from "react";
import styles from "./index.module.less";
import { getTableColumns, getSearchColumns, getCreateColumns, getCreateChildColumns } from "./constant";
import { Modal, message, Button } from "antd";
import SuperTable from "@/components/SuperTable";
import cs from "classnames";
import { getDictList, createDict, updateDict, deleteDict } from "@/api/modules/system";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import useUrl from "@/hooks/useUrl";
import { cloneDeep, omit } from "lodash";
import SearchBox from "@/components/SearchBox";
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import CreateForm from "@/components/CreateForm";
import ChildDict from "./components/ChildDict";

export default () => {
	const { navigate } = useUrl();
	const createFormRef = useRef<HTMLDivElement>(null);
	const dataTableRef = useRef<HTMLDivElement>(null);
	const [params, setParams] = useState({});
	const [defaultValues, setDefaultValues] = useState(null);
	const [isShowChildDialog, setIsShowChildDialog] = useState(false);
	const [parentId, setParentId] = useState<string | number>('-1');

	const handleRequest = async (params: any, sortInfo: any) => {
		const paramsCopy = cloneDeep(params);
		const newParams = omit(paramsCopy, ['pageSize', 'current'])
		const requestData: any = {
			parentId:"-1",
			page: {
				pageSize: params.pageSize,
				pageNum: params.current
			},
			...newParams
		};

		const res = await getDictList(requestData);
		return {
			total: res?.data?.total ?? 0,
			data: res?.data?.list ?? []
		};
	};

	const view = {
			label: "查看",
			value: "view"
		},
		edit = {
			label: "编辑",
			value: "edit"
		},
		deleteEnum = {
			label: "删除",
			value: "delete"
		};

	const newColumns = [
		...getTableColumns({ params  }),
		{
			title: "操作",
			width: 100,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "view":
						setDefaultValues(record);
						setIsShowChildDialog(true)
						break;
					case "edit":
						handleShowCreateModel(record, '-1');
						break;
					case "delete":
						handleDeleteDict(record);
						break;
				}
			},
			options: (record: any) => {
				return [view, edit, deleteEnum];
			}
		}
	];

	const NEW_SEARCH_COLUMNS = useMemo(() => {
		return getSearchColumns();
	}, []);
	
	const CREATE_COLUMNS = useMemo(() => {
		return parentId === '-1' ? getCreateColumns() : getCreateChildColumns();
	}, [parentId]);

	const handleSearch = (e: any) => {
		setParams(e);
	};


	const handleCreate = (formData: any) => {
		const requestData = {
			...formData,
			parentId: parentId,
			id: defaultValues?.id
		}
		if(defaultValues) {
			updateDict(requestData).then((res: any) => {
				if(res.code === 200) {
					message.success("字典更新成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 编辑成功后不清空defaultValues，保持当前编辑的数据状态
				}
			})
		} else {
			createDict(requestData).then((res: any) => {
				if(res.code === 200) {
					message.success("字典创建成功~");
					createFormRef?.current?.closeModel();
					dataTableRef?.current?.reload();
					// 新增成功后清空defaultValues
					setDefaultValues(null);
				}
			})
		}
	}

	const handleDeleteDict = (row: any, callBack?: any) => {
		Modal.confirm({
			icon: null,
			title: "删除提示？",
			content: `确认删除${row?.name || row?.label}吗？`,
			closable: true,
			onOk: c => {
				deleteDict({ id: row?.id }).then((res: any) => {
					if (res?.code === RESULT_CODES.SUCCESS) {
						message.success("删除成功");
						c?.();
						dataTableRef?.current?.reload();
						callBack && callBack();
					}
				});
			}
		});
	}

	const handleShowCreateModel = (record: any, parentId?:string) => {
		parentId && setParentId(parentId);
		setDefaultValues(record);
		createFormRef?.current?.showModel();
	}
	
	return (
		<div className={styles.flexContainer}>
			{
				isShowChildDialog &&
				<ChildDict
					parentRow={defaultValues}
					onEdit={handleShowCreateModel}
					onDelete={handleDeleteDict}
					onCloseChild={() => setIsShowChildDialog(false)}
				/>
			}
			<CreateForm 
				title={defaultValues ? "编辑字典" : "创建字典"} 
				columns={CREATE_COLUMNS} 
				onCreate={handleCreate} 
				ref={createFormRef} 
				defaultValues={defaultValues}
			>
				<></>
			</CreateForm>
			<div className={styles.rightModule}>
				<SearchBox columns={NEW_SEARCH_COLUMNS} onSearch={handleSearch} >
					<div></div>
				</SearchBox>
				<div
					className={cs({
						[styles.container]: true
					})}
				>
					<div className={styles.operation_group}>
						<Button icon={<PlusOutlined /> } type="primary" onClick={() => handleShowCreateModel(null, '-1')}>新增</Button>
						{/* <Button icon={<DeleteOutlined />} type="default">删除</Button> */}
					</div>
					<SuperTable
						params={{
							...params,
						}}
						ref={dataTableRef}
						// bordered
						rowKey="id"
						columns={newColumns}
						request={handleRequest}
						scroll={{ x: "900" }}
					/>
				</div>
			</div>

		</div>
	);
};
